const baseURL = 'http://localhost:8081';

const defaultHeaders = {
	'Content-Type': 'application/json',
};

function requestInterceptor(options) {
	options.header = { ...defaultHeaders };
	options.url = baseURL + options.url;
	return options;
}

function responseInterceptor(response) {
	const { statusCode, data } = response;
	if (statusCode === 200) {
		return data;
	} else {
		return Promise.reject(data);
	}
}

function handleError(error) {
	console.error('请求出错:', error);
	uni.showToast({
		title: '请求失败，请稍后重试',
		icon: 'none',
	});
	return Promise.reject(error);
}

function httpRequest(options) {
	return new Promise((resolve, reject) => {
		options = requestInterceptor(options);

		uni.request({
			...options,
			success: (response) => {
				const result = responseInterceptor(response);
				resolve(result);
			},
			fail: (error) => {
				handleError(error);
				reject(error);
			},
		});
	});
}

function get(url, params = {}) {
	return httpRequest({
		url,
		method: 'GET',
		data: params,
	});
}

function post(url, data = {}) {
	return httpRequest({
		url,
		method: 'POST',
		data,
	});
}

function put(url, data = {}) {
	return httpRequest({
		url,
		method: 'PUT',
		data,
	});
}

function del(url, data = {}) {
	return httpRequest({
		url,
		method: 'DELETE',
		data,
	});
}

export default {
	get,
	post,
	put,
	del,
};
